<template>
  <div>
    <el-dialog :visible.sync="formVisible" @close="handleCancel" width='654px' class="dialog_details">
      <div slot="title" class="dialog-title">{{postid?'修改职位':'添加职位'}}</div>
      <el-card class="el-card-border">
        <el-form :ref="formName" :label-position="labelPosition" :model="formFieldsData" label-width="100px" :rules="addrules">
          <el-form-item label="账号：" v-if="formFieldsData.request_type==1" prop='mobile'>
            <el-input v-model="formFieldsData.mobile" type='number'></el-input>
          </el-form-item>
          <el-form-item label="公司名称：" prop='name'>
            <el-input v-model="formFieldsData.name" v-if="formFieldsData.request_type==1"></el-input>
            <span v-else>{{formFieldsData.name}}</span>
          </el-form-item>
          <el-form-item label="职位类型：" prop='postid'>
            <el-cascader
              v-model="formFieldsData.postid"
              :options="postTypeList"
              :props='optionProps'
              :show-all-levels="false"
              @change='postChange'
              style="width:100%"
              placeholder="请选择职位类型"
              ></el-cascader>
          </el-form-item>
          <el-form-item label="工作类型：" v-if="postType=='DRIVER_TYPE'||formFieldsData.workType">
            <div class="flex_box">
              <p class="attr_item" 
                :class="formFieldsData.workType==item.value_id?'cur':''" 
                @click="workTypeChange(item.value_id)" 
                v-for="(item,index) in workTypeList" :key="index+'work'">{{item.value_name}}</p>
            </div>
          </el-form-item>
          <salaryForm ref='salary' @salaryChange='salaryChange'></salaryForm>
          <el-form-item prop='attr_value_id' class="welfare_box">
            <span slot="label"><i>*</i> 福利待遇（可多选）：</span>
            <div class="flex_box_wrap flex1">
              <p class="attr_item" v-for="(item,index) in welfareList" :class="item.isSelected?'cur':''" @click="welfareChange(item)" :key='index'>{{item.value_name}}</p>
              <p class="treament_box" v-for="(item,index) in treamentList" :key='index+1+"aa"'>
                <el-input placeholder="最多输入6个字" class="treamentipt" v-model="item.name" @blur="treatmentBlur" :disabled="item.disabled" :data-index='index'></el-input>
                <span class="el-icon-circle-close close_btn" alt="" @click="delTreatment(index)" ></span>
              </p>
              <p class="attr_item" @click="addTreatment">+其他</p>
            </div>
          </el-form-item>
          <el-form-item label="工作城市：" prop='district'>
            <addr ref='addr' @addrChange='postaddrChange'></addr>
          </el-form-item>
          <el-form-item label="工作地点：" prop='address'>
            <el-input v-model="formFieldsData.address"></el-input>
          </el-form-item>
          <el-form-item label="招聘人数：" prop='number_recruiters'>
            <el-input v-model="formFieldsData.number_recruiters" type='number'></el-input>
          </el-form-item>
          <!-- <el-form-item label="年龄范围：" prop='age_max'>
            <div class="flex_box wages">
              <el-input v-model="formFieldsData.age_min" class="flex1" type='number'></el-input>
              <span>至</span>
              <el-input v-model="formFieldsData.age_max" class="flex1" type='number'></el-input>
              <span>岁</span>
            </div>
          </el-form-item> -->
          <el-form-item label="年龄要求：" prop='age'>
            <div class="flex_box">
              <p class="attr_item" 
                :class="formFieldsData.age==item.value_id?'cur':''" 
                @click="ageChange(item.value_id)" 
                v-for="(item,index) in ageList" :key='index'>{{item.value_name}}</p>
            </div>
          </el-form-item>
          <el-form-item label="经验要求：" prop='experience'>
            <div class="flex_box">
              <p class="attr_item" 
                :class="formFieldsData.experience==item.value_id?'cur':''" 
                @click="experienceChange(item.value_id)" 
                v-for="(item,index) in experienceList" :key='index'>{{item.value_name}}</p>
            </div>
          </el-form-item>
          <el-form-item label="岗位职责：">
            <el-input type="textarea" v-model="formFieldsData.duty"></el-input>
          </el-form-item>
          <el-form-item label="联系人：" prop='contacts'>
            <el-input type="text" v-model="formFieldsData.contacts"></el-input>
          </el-form-item>
          <el-form-item label="联系电话：" prop='contacts_mobile'>
            <el-input type="number" v-model="formFieldsData.contacts_mobile"></el-input>
          </el-form-item>
        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel" size='medium'>取消</el-button>
        <el-button type="primary" @click="addSubmit" size='medium'>发布</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import addr from '@/components/addr/index.vue'
import salaryForm from '@/components/salary'
import formOperate from '@/layout/mixin/formOperate'
import {addPost} from '@/api/talent.js'
export default {
  mixins: [formOperate],
  name: 'Index',
  data() {
    return {
      url:'/profession/admin/attrValue',
      id:'',
      formName:'addPost',
      formVisible:false,
      formFieldsData: {
        attr_value_id:'',
        province:'',
        city:'',
        district:'',
        address:'',
        contacts:'',
        contacts_mobile:'',
        treatment:'',
        age_max:'',
        age_min:'',
        duty:'',
        number_recruiters:'',
        salary_type:1,
        min_money:'',
        max_money:'',
        source:'5',
        name:'',
        mobile:'',
        request_type:'',
        company_id:'',
        diy_post_type:'',
        postid:'',// 职位类型
        workType:'', // 工作类型
        experience:'',// 经验
        age:''
      },
      optionProps: {
        value: 'value_id',
        label: 'value_name',
        children: 'child'
      },
      treamentList:[], // 其他福利待遇
      addrules:{
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入公司账号', trigger: 'blur' }
        ],
        postid: [
          { required: true, message: '请选择职位类型', trigger: 'blur' }
        ],
        contacts: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        contacts_mobile: [
          { required: true, message: '请输入联系人电话', trigger: 'blur' }
        ],
        district: [
          { required: true, message: '请选择工作城市', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入工作地区', trigger: 'blur' }
        ],
        // age: [
        //   { required: true, message: '请选择年龄要求', trigger: 'click' }
        // ],
        experience:[
          { required: true, message: '请选择经验要求', trigger: 'click' }
        ],
        number_recruiters:[
          { required: true, message: '请输入招聘人数', trigger: 'blur' }
        ]
      },
      postType:'', // 职位类型type
      area:{}, // 工作城市
      postid:'', // 修改职位id
      userid:'',
      company_id:''
    }
  },
  mounted() {
    this.GetAttrData('WORK_TYPE')
    this.GetAttrData('TREA')
    this.GetAttrData('AGE_REQUIRE')
    this.GetAttrData('EXP_REQUIRE')
  },
  methods: {
    // 显示
    show(list,entry,name,company_id,item) {
      this.postTypeList = list
      this.formFieldsData.request_type = entry
      if (entry == 2) {
        this.formFieldsData.name = name
        this.formFieldsData.company_id = company_id
      }
      this.postid = item ? item.id : ''
      this.userid = item ? item.user_id : ''
      this.company_id = item ? item.company_id : ''
      this.formVisible = true
      this.treamentList = []
      this.postType = ''
      if (this.postid) {
        this.$http.get('/profession/admin/post/'+this.postid).then(response => {
          let info = response.data
          for (let key in this.formFieldsData) {
            if (info[key]) {
              this.formFieldsData[key] = info[key]
            }
          }
          this.formFieldsData.mobile = info.user_info.mobile
          this.formFieldsData.name = info.company_info.name
          this.formFieldsData.age = info.user_info.age || ''
          this.formFieldsData.diy_post_type = info.diy_post_type
          this.formFieldsData.postid = this.getAttrId(info.value_list,'POST_TYPE')
          this.formFieldsData.workType = this.getAttrId(info.value_list,'WORK_TYPE').toString()
          if (this.workType) {
            this.postType = this.drivingType
          }
          this.formFieldsData.experience = this.getAttrId(info.value_list,'EXP_REQUIRE').toString()
          this.formFieldsData.age = this.getAttrId(info.value_list,'AGE_REQUIRE').toString()
          if (info.treatment) {
            let arr = info.treatment.split(',')
            arr.forEach(res=>{
              this.treamentList.push({
                name:res,
                disabled:true
              })
            })
          }
          let trea = this.getAttr(info.value_list,'TREA')
          this.welfareList.forEach(res=>{
            let idx = trea.findIndex(res1=>{
              return res1.value_id == res.value_id
            })
            if (idx > -1) {
              this.$set(res,'selected',true)
            }
          })
          this.area = {
            pid:info.province,
            cid:info.city,
            did:info.district || '',
            pname:info.province_name,
            cname:info.city_name,
            dname:info.district_name || ''
          }
          this.$nextTick(()=>{
            this.$refs.addr.updateData(this.area)
            this.$refs.salary.updateData(this.formFieldsData.salary_type,this.formFieldsData.min_money,this.formFieldsData.max_money)
          })
        })
      } else {
        this.postType = ''
        this.area = {
          pid:'',
          cid:'',
          did: '',
          pname:'',
          cname:'',
          dname:''
        }
        this.$nextTick(()=>{
          this.$refs.addr.updateData(this.area)
          this.$refs.salary.updateData(this.formFieldsData.salary_type,this.formFieldsData.min_money,this.formFieldsData.max_money)
        })
      }
    },
    hide() {
      this.formVisible = false
    },
    // 提交
    addSubmit() {
      this.$refs[this.formName].validate((valid) => {
        if (valid) {
          let query = this.formFieldsData
          let arr = []
          if (query.postid) {
            arr.push(query.postid)
          }
          if (query.workType) {
            arr.push(query.workType)
          }
          if (query.experience) {
            arr.push(query.experience)
          }
          if (query.age) {
            arr.push(query.age)
          }
          let welfare = []
          this.welfareList.forEach(res=>{
            if (res.isSelected) {
              welfare.push(res.value_id)
              arr.push(res.value_id)
            }
          })
          let treatment = []
          this.treamentList.forEach(res=>{
            treatment.push(res.name)
          })
          query.treatment = treatment.toString()
          query.attr_value_id = arr.toString()
          if(welfare.length==0 && treatment.length==0) {
            this.$message.error('请选择福利待遇');
            return
          }
          if (query.salary_type!=3 && query.min_money == '') {
            this.$message.error('请选择期望薪资');
            return
          }
          let param = {...query}
          delete param.postid
          delete param.workType
          delete param.experience
          delete param.age
          if (this.postid) {
            if (query.request_type == 1) {
              let userParam = {
                mobile:query.mobile
              }
              this.$http.put('/user/admin/user/'+this.userid, userParam).then(() => {
                let companyParam = {
                  name:query.name,
                  license_name:query.name
                }
                this.$http.put('/profession/admin/company/'+this.company_id, companyParam).then(() => {
                  this.$http.put('/profession/admin/post/'+this.postid, param).then(() => {
                    this.$emit('success')
                    this.handleCancel()
                  })
                })
              })
            } else {
              this.$http.put('/profession/admin/post/'+this.postid, param).then(() => {
                this.$emit('success')
                this.handleCancel()
              })
            }
          } else {
            addPost(query).then(()=>{
              this.$emit('success')
              this.handleCancel()
            })
          }
        } else {
          return false
        }
      })
    },
    // 职位类型选择
    postChange(e) {
      this.formFieldsData.postid = e[1]
      let idx = this.postTypeList.findIndex(res=>{
        return res.value_id == e[0]
      })
      this.postType = this.postTypeList[idx].value_type
      this.formFieldsData.diy_post_type = ''
      if (this.postType != this.drivingType) {
        this.formFieldsData.workType = ''
      }
    },
    // 工作类型
    workTypeChange(id) {
      this.formFieldsData.workType = id
    },
    // 经验要求
    experienceChange(id) {
      this.formFieldsData.experience = id
    },
    // 年龄要求
    ageChange(id) {
      this.formFieldsData.age = id
    },
    // 选择薪资
    salaryChange(val) {
      this.formFieldsData.salary_type = val.salary_type
      this.formFieldsData.min_money = val.min_money
      this.formFieldsData.max_money = val.max_money
    },
    // 工作地址
    postaddrChange(val) {
      this.formFieldsData.province = val.provinceid
      this.formFieldsData.city = val.cityid
      this.formFieldsData.district = val.districtid
    },
    // 福利待遇多选
    welfareChange(item) {
      if (item.isSelected) {
        item.isSelected = false
      } else {
        this.$set(item,'isSelected',true)
      }
    },
    // 添加福利待遇
    addTreatment() {
      this.treamentList.push({
        id:this.treamentList.length+1,
        name:'',
        disabled:false
      })
    },
    // 福利待遇input失去焦点
    treatmentBlur(e) {
      let val = e.detail.value
      let idx = this.welfareList.findIndex(res=>{
        return res.value_name == val
      })
      if (idx > -1) {
        uni.showToast({
          title:'已有该福利待遇，请重新输入'
        })
        return
      }
      let index = e.currentTarget.dataset.index
      this.treamentList[index].disabled = true
    },
    // 福利待遇其他多选
    treatmentChange(item) {
      if (item.isSelected) {
        item.isSelected = false
      } else {
        this.$set(item,'isSelected',true)
      }
    },
    // 删除新增的福利待遇
    delTreatment(index) {
      this.treamentList.splice(index,1)
    }
  },
  components:{
    addr,
    salaryForm
  }
}
</script>
<style lang="scss" scoped>
  @import '~@/styles/element-variables.scss';
  .attr_item{
    min-width: 95px;
    height: 32px;
    line-height: 32px;
    padding: 0 16px;
    border:1px solid #eee;
    margin: 0 10px 10px 0;
    text-align: center;
    cursor: pointer;
    position: relative;
  }
  .attr_item.cur{
    border-color:$--color-primary;
    background: url('~@/assets/images/icon1.png') no-repeat right bottom;
  }
  .wages span{
    margin:0 10px;
  }
  .wages{
    margin-bottom: 20px;
  }
  .welfare_box{
    position: relative;
  }
  .welfare_box .label{
    position: absolute;
    left:-100px;
    width: 100px;
    padding-right: 12px;
    box-sizing: border-box;
    font-weight: bold;
    line-height: 26px;
    font-size: 14px;
  }
  .welfare_box i{
    color:#d26a5c;
    font-weight: bold;
    margin-right: 4px;
  }
  .photo_box{
    text-align: center;
  }
  .photo_box img{
    display:block;
    margin:0 auto 10px;
    width: 150px;
  }
  .addform{
    padding-right: 20px;
    box-sizing: border-box;
    height:600px;
    overflow-y:auto;
  }
  .treament_box{
    position: relative;
  }
  .close_btn{
    position: absolute;
    right: 12px;
    top:-6px;
    cursor: pointer;
  }
  .treamentipt{
    width:136px;
    margin: 0 20px 10px 0;
  }
</style>